/**
 * AI聊天界面组件
 * 提供用户与AI进行对话的功能，包括：
 * - 创建和管理对话
 * - 发送和接收消息
 * - 显示对话历史
 * - 响应式布局支持
 * - 用户认证和权限控制
 * - 实时消息更新
 * - 错误处理和用户提示
 * - Markdown格式支持
 */

<template>
  <!-- 主容器 -->
  <div class="ai-chat-container">
    <!-- 聊天内容区域 -->
    <div class="chat-container">
      <!-- 左侧对话列表 -->
      <div class="sidebar">
        <!-- 侧边栏头部 -->
        <div class="sidebar-header">
          <h2>会话列表</h2>
          <button class="new-chat-btn" @click="showCreateDialog">
            <span class="plus-icon">+</span> 新对话
          </button>
        </div>
        <!-- 对话列表 -->
        <div class="conversation-list">
          <div
            v-for="conversation in conversations"
            :key="conversation.conversationId"
            class="conversation-item"
            :class="{ active: currentConversationId === conversation.conversationId }"
            @click="selectConversation(conversation.conversationId)"
          >
            <!-- 对话信息 -->
            <div class="conversation-info">
              <div class="conversation-title">{{ conversation.title }}</div>
              <div class="conversation-preview">
                {{ conversation.lastMessage || '暂无消息' }}
              </div>
            </div>
            <!-- 对话操作按钮 -->
            <div class="conversation-actions">
              <button
                class="delete-button"
                @click.stop="handleDeleteConversation(conversation.conversationId)"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-main">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="header-left">
            <button class="back-button" @click="goHome">
              <span class="arrow-icon">←</span> 返回首页
            </button>
          </div>
          <h2>{{ currentConversationTitle }}</h2>
        </div>
        
        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <!-- 空状态提示 -->
          <div v-if="!currentConversationId" class="empty-state">
            <div class="empty-icon">💬</div>
            <h3>开始一个新的对话</h3>
            <p>选择左侧的对话或创建一个新的对话来开始聊天</p>
          </div>
          <template v-else>
            <!-- 加载状态 -->
            <div v-if="messages.length === 0" class="loading-messages">
              <div class="skeleton">
                <div class="skeleton-line"></div>
                <div class="skeleton-line"></div>
                <div class="skeleton-line"></div>
              </div>
            </div>
            <!-- 消息列表 -->
            <div
              v-for="(message, index) in messages"
              :key="index"
              class="message-container"
              :class="{'user-container': message.role === 'user'}"
            >
              <div class="message" :class="message.role">
                <!-- AI头像 -->
                <div class="message-avatar" v-if="message.role === 'assistant'">
                  <div class="ai-avatar">
                    <img 
                      src="https://aaan.oss-cn-beijing.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_2024-11-21_141916_917.png" 
                      alt="AI头像" 
                      @error="handleAvatarError"
                      style="width: 100%; height: 100%; object-fit: cover;">
                  </div>
                </div>
                <!-- 消息内容 -->
                <div class="message-content">
                  <div class="message-text" v-html="formatMessage(message.content)"></div>
                  <div class="message-time">
                    {{ formatDateTime(message.createdAt) }}
                  </div>
                </div>
                <!-- 用户头像 -->
                <div class="message-avatar" v-if="message.role === 'user'" @click="goToUserCenter">
                  <div class="user-avatar" v-if="user && user.avatar">
                    <img :src="user.avatar" alt="用户头像">
                  </div>
                  <div class="user-avatar" v-else>
                    <span>{{ userInitial }}</span>
                  </div>
                </div>
              </div>
            </div>
            <!-- AI正在输入提示 -->
            <div v-if="isTyping" class="message-container">
              <div class="message assistant">
                <div class="message-avatar">
                  <div class="ai-avatar">
                    <img 
                      src="https://aaan.oss-cn-beijing.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_2024-11-21_141916_917.png" 
                      alt="AI头像" 
                      @error="handleAvatarError"
                      style="width: 100%; height: 100%; object-fit: cover;">
                  </div>
                </div>
                <div class="message-content">
                  <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 消息列表底部锚点 -->
            <div ref="messagesEnd"></div>
          </template>
        </div>
          
        <!-- 消息输入区域 -->
        <div class="chat-input-container">
          <div class="input-wrapper">
            <textarea 
              v-model="newMessage"
              placeholder="输入消息..."
              @keydown.enter.prevent="handleSendMessage"
              class="message-input"
              rows="3"
            ></textarea>
            <button
              class="send-button"
              :disabled="!newMessage.trim() || isTyping"
              @click="handleSendMessage"
            >
              发送
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建新对话对话框 -->
    <div v-if="dialogVisible" class="dialog-overlay" @click="dialogVisible = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>创建新对话</h3>
          <button class="close-button" @click="dialogVisible = false">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
        <div class="dialog-body">
          <div class="dialog-icon">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
            </svg>
          </div>
          <form @submit.prevent="createNewConversation" class="dialog-form">
            <div class="form-group">
              <label>对话标题</label>
              <div class="input-wrapper">
                <input
                  v-model="dialogForm.title"
                  type="text"
                  placeholder="请输入对话标题"
                  maxlength="50"
                  ref="titleInputRef"
                  class="form-input"
                >
                <span class="word-count" :class="{ 'near-limit': dialogForm.title.length > 40 }">
                  {{ dialogForm.title.length }}/50
                </span>
              </div>
            </div>
            <div class="dialog-footer">
              <button type="button" class="cancel-button" @click="dialogVisible = false">
                取 消
              </button>
              <button type="submit" class="submit-button">
                创 建
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 创建成功弹窗 -->
    <div v-if="successDialogVisible" class="success-dialog-overlay" @click="successDialogVisible = false">
      <div class="success-dialog" @click.stop>
        <div class="success-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
            <polyline points="22 4 12 14.01 9 11.01"></polyline>
          </svg>
        </div>
        <div class="success-message">对话创建成功</div>
        <button class="success-button" @click="successDialogVisible = false">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import { getUserDetailsInfo } from '@/api/user'
import { 
  getConversations,
  getMessageHistory,
  createConversation,
  deleteConversation,
  sendMessage
} from '@/api/ai'

export default {
  name: 'AIChatView',
  components: {
  },
  setup() {
    const router = useRouter()
    // 响应式数据
    const conversations = ref([]) // 对话列表
    const messages = ref([]) // 当前对话的消息列表
    const newMessage = ref('') // 新消息输入框内容
    const currentConversationId = ref(null) // 当前选中的对话ID
    const currentConversationTitle = ref('选择一个对话') // 当前对话标题
    const isTyping = ref(false) // AI是否正在输入
    const user = ref(null) // 用户信息
    const userInitial = ref('U') // 用户头像首字母
    const dialogVisible = ref(false) // 创建对话对话框是否可见
    const successDialogVisible = ref(false) // 创建成功弹窗是否可见
    const dialogForm = ref({
      title: '' // 新对话标题
    })
    const titleInputRef = ref(null) // 标题输入框引用
    const messagesContainer = ref(null) // 消息容器引用
    const messagesEnd = ref(null) // 消息列表底部引用

    /**
     * 显示创建对话对话框
     * 设置默认标题并自动聚焦输入框
     */
    const showCreateDialog = async () => {
      dialogVisible.value = true
      dialogForm.value.title = '新对话'
      
      await nextTick()
      if (titleInputRef.value) {
        titleInputRef.value.focus()
        titleInputRef.value.select()
      }
    }

    /**
     * 获取用户信息
     * 包括用户名、头像等信息
     */
    const fetchUserInfo = async () => {
      try {
        const response = await getUserDetailsInfo()
        if (response.code === 200 && response.data) {
          user.value = response.data
          if (user.value.userName) {
            userInitial.value = user.value.userName.charAt(0).toUpperCase()
          }
          // 从 ossImages 中获取头像 URL
          if (user.value.ossImages && user.value.ossImages.length > 0) {
            const headImage = user.value.ossImages.find(img => img.relationType === 'head')
            if (headImage) {
              user.value.avatar = headImage.url
            }
          }
        }
      } catch (error) {
        showMessage('获取用户信息失败', 'error')
      }
    }

    /**
     * 获取所有对话列表
     * 如果当前没有选中的对话，则自动选择第一个对话
     */
    const fetchConversations = async () => {
      try {
        const response = await getConversations()
        
        if (response.code === 200 && response.data && response.data.data) {
          conversations.value = response.data.data
          
          if (!currentConversationId.value && conversations.value.length > 0) {
            selectConversation(conversations.value[0].conversationId)
          }
        }
      } catch (error) {
        showMessage('获取对话列表失败', 'error')
      }
    }

    /**
     * 选择对话
     * @param {number} conversationId - 要选择的对话ID
     */
    const selectConversation = async (conversationId) => {
      if (currentConversationId.value === conversationId) return
      
      currentConversationId.value = conversationId
      messages.value = []
      
      const conversation = conversations.value.find(c => c.conversationId === conversationId)
      if (conversation) {
        currentConversationTitle.value = conversation.title
      }
      
      await fetchMessages(conversationId)
      
      // 如果没有消息，添加引导消息
      if (messages.value.length === 0) {
        messages.value.push({
          role: 'assistant',
          content: '请说出你的想法，我将尽力帮助你。',
          createdAt: new Date().toISOString()
        })
      }
      
      await nextTick()
      scrollToBottom()
    }

    /**
     * 获取对话消息历史
     * @param {number} conversationId - 对话ID
     */
    const fetchMessages = async (conversationId) => {
      try {
        const response = await getMessageHistory(conversationId)
        
        if (response.code === 200 && response.data && response.data.data) {
          messages.value = response.data.data
        }
      } catch (error) {
        showMessage('获取消息历史失败', 'error')
      }
    }

    /**
     * 创建新对话
     * 验证表单并发送创建请求
     */
    const createNewConversation = async () => {
      try {
        if (!dialogForm.value.title.trim()) {
          showMessage('请输入对话标题', 'error')
          return
        }

        const token = sessionStorage.getItem('token') || localStorage.getItem('token')
        if (!token) {
          showMessage('未登录或登录已过期，请重新登录', 'error')
          return
        }

        const response = await createConversation(dialogForm.value.title)
        
        if (response.code === 200 && response.data) {
          const nestedResponse = response.data
          if (nestedResponse.code === 200 && nestedResponse.data) {
            const conversationId = nestedResponse.data
            
            // 显示成功弹窗
            dialogVisible.value = false
            successDialogVisible.value = true
            
            await fetchConversations()
            
            setTimeout(() => {
              selectConversation(conversationId)
            }, 100)
          } else {
            throw new Error(nestedResponse.message || '创建对话失败')
          }
        } else {
          throw new Error(response.message || '创建对话失败')
        }
      } catch (error) {
        showMessage(error.message || '创建对话失败，请稍后重试', 'error')
      }
    }

    /**
     * 删除对话
     * @param {number} conversationId - 要删除的对话ID
     */
    const handleDeleteConversation = async (conversationId) => {
      if (!confirm('确认删除该对话？此操作不可撤销。')) {
        return
      }
      
      try {
        const response = await deleteConversation(conversationId)
        
        if (response.code === 200 && response.data) {
          showMessage('删除对话成功', 'success')
          
          if (currentConversationId.value === conversationId) {
            currentConversationId.value = null
            currentConversationTitle.value = '选择一个对话'
            messages.value = []
          }
          
          await fetchConversations()
        } else {
          throw new Error(response.message || '删除失败')
        }
      } catch (error) {
        showMessage('删除对话失败: ' + (error.message || '未知错误'), 'error')
      }
    }

    /**
     * 发送消息
     * 处理新对话创建和消息发送
     */
    const handleSendMessage = async () => {
      if (!newMessage.value.trim() || isTyping.value) return
      
      // 获取并验证 token
      const token = sessionStorage.getItem('token') || localStorage.getItem('token')
      if (!token) {
        showMessage('未登录或登录已过期，请重新登录', 'error')
        return
      }
      
      if (!currentConversationId.value) {
        try {
          const response = await createConversation('新对话')
          
          if (response.code === 200 && response.data) {
            const nestedResponse = response.data
            if (nestedResponse.code === 200 && nestedResponse.data) {
              currentConversationId.value = nestedResponse.data
              currentConversationTitle.value = '新对话'
            } else {
              throw new Error(nestedResponse.message || '创建对话失败')
            }
          } else {
            throw new Error(response.message || '创建对话失败')
          }
        } catch (error) {
          showMessage(error.message || '创建对话失败，请稍后重试', 'error')
          return
        }
      }
      
      const message = newMessage.value.trim()
      newMessage.value = ''
      
      const userMessage = {
        role: 'user',
        content: message,
        createdAt: new Date().toISOString()
      }
      messages.value.push(userMessage)
      
      await nextTick()
      scrollToBottom()
      
      isTyping.value = true
      
      try {
        const response = await sendMessage({
          message,
          conversationId: currentConversationId.value,
          token
        })
        
        isTyping.value = false
        
        if (response.code === 200 && response.data) {
          const nestedResponse = response.data
          
          if (nestedResponse.code === 200 && nestedResponse.data) {
            const aiMessage = {
              role: 'assistant',
              content: nestedResponse.data,
              createdAt: new Date().toISOString()
            }
            
            messages.value.push(aiMessage)
            await fetchConversations()
            
            await nextTick()
            scrollToBottom()
          } else {
            showMessage(nestedResponse.message || '发送消息失败', 'error')
          }
        } else {
          showMessage(response.message || '发送消息失败，服务器返回非预期响应', 'error')
        }
      } catch (error) {
        isTyping.value = false
        showMessage('发送消息失败，请稍后重试', 'error')
      }
    }

    /**
     * 格式化消息内容
     * 将Markdown内容转换为HTML
     * @param {string} content - 消息内容
     * @returns {string} 格式化后的HTML内容
     */
    const formatMessage = (content) => {
      if (!content) return ''
      
      try {
        // 配置marked选项
        marked.setOptions({
          breaks: true, // 将换行符转换为<br>
          gfm: true, // 启用GitHub风格的Markdown
        })
        
        // 渲染Markdown为HTML
        let html = marked.parse(content)
        
        // 处理链接，使其在新窗口打开
        html = html.replace(/<a href=/g, '<a target="_blank" rel="noopener noreferrer" href=')
        
        return html
      } catch (error) {
        console.error('Markdown渲染错误:', error)
        // 如果解析失败，退回到基本的文本格式化
        return content.replace(/\n/g, '<br>')
      }
    }

    /**
     * 格式化日期时间
     * 根据时间差显示不同的格式
     * @param {string} dateString - ISO格式的日期字符串
     * @returns {string} 格式化后的日期时间字符串
     */
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
      
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        const weekdays = ['日', '一', '二', '三', '四', '五', '六']
        return `星期${weekdays[date.getDay()]} ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
      }
      
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    /**
     * 滚动到消息列表底部
     */
    const scrollToBottom = () => {
      if (messagesEnd.value) {
        messagesEnd.value.scrollIntoView({ behavior: 'smooth' })
      }
    }

    /**
     * 返回首页
     */
    const goHome = () => {
      router.push('/')
    }

    /**
     * 跳转到用户中心
     */
    const goToUserCenter = () => {
      router.push('/user')
    }

    /**
     * 显示消息提示
     * @param {string} message - 提示消息
     * @param {string} type - 消息类型（success/error）
     */
    const showMessage = (message, type = 'success') => {
      ElMessage({
        message,
        type,
        duration: 2000
      })
    }

    /**
     * 处理头像加载错误
     * 设置默认头像
     * @param {Event} e - 错误事件对象
     */
    const handleAvatarError = (e) => {
      // 设置默认头像
      e.target.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="%234b5563"><circle cx="12" cy="12" r="10" fill="%23f3f4f6" /><text x="12" y="16" text-anchor="middle" fill="%234b5563" font-size="12" font-weight="bold">AI</text></svg>'
    }

    // 组件挂载时初始化数据
    onMounted(() => {
      fetchUserInfo()
      fetchConversations()
    })

    return {
      conversations,
      messages,
      newMessage,
      currentConversationId,
      currentConversationTitle,
      isTyping,
      user,
      userInitial,
      dialogVisible,
      successDialogVisible,
      dialogForm,
      titleInputRef,
      messagesContainer,
      messagesEnd,
      showCreateDialog,
      selectConversation,
      handleDeleteConversation,
      handleSendMessage,
      formatMessage,
      formatDateTime,
      goHome,
      createNewConversation,
      goToUserCenter,
      handleAvatarError
    }
  }
}
</script>

<style scoped>
/* 主容器样式 */
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  position: relative;
}

/* 聊天内容区域样式 */
.chat-container {
  display: flex;
  position: fixed;
  top: 60px; /* 导航栏高度 */
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  background-color: #f5f5f5;
  overflow: hidden;
  z-index: 100;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-right: 1px solid #e0e0e0;
  z-index: 100;
  overflow: hidden;
}

/* 侧边栏头部样式 */
.sidebar-header {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #eaeaea;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 新建对话按钮样式 */
.new-chat-btn {
  display: flex;
  align-items: center;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.new-chat-btn:hover {
  background-color: #66b1ff;
}

.plus-icon {
  margin-right: 4px;
  font-weight: bold;
}

/* 对话列表样式 */
.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.conversation-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  background-color: #f9f9f9;
}

.conversation-item:hover {
  background-color: #f0f0f0;
}

.conversation-item.active {
  background-color: #e1f5fe;
}

.conversation-info {
  flex: 1;
  overflow: hidden;
}

.conversation-title {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-preview {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.conversation-item:hover .conversation-actions {
  opacity: 1;
}

.delete-button {
  background: none;
  border: none;
  color: #f56c6c;
  font-size: 12px;
  cursor: pointer;
  padding: 4px 8px;
}

.delete-button:hover {
  text-decoration: underline;
}

/* 聊天主区域样式 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  background-color: #f9fbfc;
}

/* 聊天头部样式 */
.chat-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #fff;
  position: relative;
  z-index: 10;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-left {
  position: absolute;
  left: 20px;
}

.back-button {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
}

.back-button:hover {
  color: #409eff;
}

.arrow-icon {
  margin-right: 4px;
}

/* 消息区域样式 */
.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message-container {
  display: flex;
  margin-bottom: 20px;
  padding: 4px 0;
}

.user-container {
  justify-content: flex-end;
}

.message {
  max-width: 80%;
  display: flex;
  align-items: flex-start;
}

.message.user {
  flex-direction: row;
}

.message.user .message-content {
  background-color: #e1f5fe;
  margin-right: 12px;
}

/* 头像样式 */
.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 12px;
  cursor: pointer;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
}

.ai-avatar, .user-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  color: #409eff;
  font-weight: bold;
}

.user-avatar {
  background-color: #409eff;
  color: white;
}

.user-avatar img, .ai-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 消息内容样式 */
.message-content {
  background-color: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-text {
  line-height: 1.6;
  word-break: break-word;
}

.message-text :deep(pre) {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 10px 0;
  font-family: monospace;
}

.message-text :deep(code) {
  background-color: #f0f0f0;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 0.9em;
}

.message-text :deep(blockquote) {
  border-left: 4px solid #ddd;
  margin-left: 0;
  padding-left: 10px;
  color: #666;
}

.message-text :deep(ul), .message-text :deep(ol) {
  padding-left: 20px;
}

.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}

.message-text :deep(th), .message-text :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.message-text :deep(th) {
  background-color: #f2f2f2;
}

.message-text :deep(img) {
  max-width: 100%;
  border-radius: 6px;
}

.message-text :deep(h1), .message-text :deep(h2), .message-text :deep(h3),
.message-text :deep(h4), .message-text :deep(h5), .message-text :deep(h6) {
  margin-top: 16px;
  margin-bottom: 8px;
  line-height: 1.4;
}

.message-text :deep(p) {
  margin: 8px 0;
}

.message-text :deep(a) {
  color: #409eff;
  text-decoration: none;
}

.message-text :deep(a:hover) {
  text-decoration: underline;
}

.message-time {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
  text-align: right;
}

/* 输入指示器样式 */
.typing-indicator {
  display: flex;
  align-items: center;
  height: 20px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  margin: 0 2px;
  background-color: #9E9E9E;
  border-radius: 50%;
  display: inline-block;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% { transform: scale(1); }
  50% { transform: scale(1.5); }
  100% { transform: scale(1); }
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  text-align: center;
  padding: 0 20px;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #d9d9d9;
}

.empty-state h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.empty-state p {
  margin: 0;
  max-width: 300px;
}

/* 输入区域样式 */
.chat-input-container {
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
  padding: 20px;
  position: relative;
  z-index: 5;
}
  
.input-wrapper {
  display: flex;
  align-items: stretch;
  gap: 12px;
  background-color: #fff;
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.input-wrapper:focus-within {
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
}

.message-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  font-size: 14px;
  resize: none;
  transition: all 0.3s;
  height: 56px;
  line-height: 1.6;
  color: #333;
  background-color: #f9f9f9;
  box-sizing: border-box;
}

.message-input:focus {
  outline: none;
  border-color: #409eff;
  background-color: #fff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.message-input::placeholder {
  color: #909399;
}

.send-button {
  background-color: #409eff;
  color: #fff;
  min-width: 90px;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  height: 56px;
  padding: 0 24px;
  box-sizing: border-box;
  display: flex;
}

.send-button:hover:not(:disabled) {
  background-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.send-button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

/* 加载效果样式 */
.loading-messages {
  padding: 20px 0;
  text-align: center;
}

.skeleton {
  padding: 16px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  width: 70%;
  margin: 0 auto;
}

.skeleton-line {
  height: 16px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin-bottom: 12px;
  animation: pulse 1.5s infinite;
}

.skeleton-line:last-child {
  width: 60%;
  margin-bottom: 0;
}

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 12px;
  max-width: 90%;
  width: 460px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #eaeaea;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 6px;
}

.close-button:hover {
  color: #666;
}

.dialog-body {
  padding: 24px;
}

.dialog-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
  color: #409eff;
}

.dialog-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-input {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  height: 42px;
}

.form-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.input-wrapper {
  position: relative;
}

.word-count {
  position: absolute;
  right: 10px;
  bottom: 10px;
  font-size: 12px;
  color: #909399;
}

.word-count.near-limit {
  color: #e6a23c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 10px;
}

.cancel-button, .submit-button {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-button {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.cancel-button:hover {
  background-color: #e9ecef;
}

.submit-button {
  background-color: #409eff;
  border: none;
  color: white;
}

.submit-button:hover {
  background-color: #66b1ff;
}

/* 创建成功弹窗样式 */
.success-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.success-dialog {
  background-color: white;
  padding: 30px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  max-width: 90%;
  width: 360px;
}

.success-icon {
  color: #52c41a;
  margin-bottom: 16px;
}

.success-message {
  margin-bottom: 24px;
  font-size: 18px;
  color: #333;
}

.success-button {
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.success-button:hover {
  background-color: #5dd62b;
}

/* 调整移动端响应式布局 */
@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
    top: 60px;
    bottom: 0;
    margin-top: 0;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    max-height: 30vh;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
  }
  
  .chat-main {
    height: 70vh;
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-header h2 {
    width: 60%;
    margin: 0 auto;
  }
}
</style>